<template>
  <RadioGroup
    :model-value="modelValue"
    :disabled="disabled"
    @update:model-value="pickIcon"
  >
    <div class="flex flex-wrap space-x-[0.44rem]" v-bind="$attrs">
      <RadioGroupOption
        v-for="(icon, index) in icons"
        :key="icon[valueField]"
        v-slot="{ checked }"
        :name="name"
        as="template"
        :value="icon[valueField]"
      >
        <div
          v-i-tooltip="icon.tooltip"
          :class="[
            'flex h-9 w-10 cursor-pointer items-center justify-center rounded-md border border-neutral-300 p-1 text-neutral-700  dark:border-neutral-500 dark:text-neutral-200',
            { 'pointer-events-none opacity-70': disabled },

            index % 10 === 0 && index !== 0
              ? '!ml-0 mt-1'
              : index > 10 && index % 10 !== 0
                ? 'mt-1'
                : '',
            checked
              ? 'bg-neutral-200 hover:bg-neutral-200 dark:bg-neutral-800'
              : 'bg-white hover:bg-neutral-50 hover:text-neutral-900 dark:bg-neutral-700 dark:hover:bg-neutral-600 dark:hover:text-neutral-100',
          ]"
        >
          <RadioGroupLabel as="span">
            <Icon :icon="icon.icon" class="h-5 w-5" />
          </RadioGroupLabel>
        </div>
      </RadioGroupOption>
    </div>
  </RadioGroup>
</template>

<script setup>
import { ref, watch } from 'vue'
import { RadioGroup, RadioGroupLabel, RadioGroupOption } from '@headlessui/vue'

defineOptions({ inheritAttrs: false })

const props = defineProps({
  modelValue: [String, Number],
  label: String,
  disabled: Boolean,
  valueField: { type: String, default: 'icon' },
  name: String,
  icons: {
    type: Array,
    default: function () {
      return [
        'Mail',
        'PencilAlt',
        'OfficeBuilding',
        'Phone',
        'Calendar',
        'Collection',
        'Bell',
        'AtSymbol',
        'Briefcase',
        'Chat',
        'CheckCircle',
        'BookOpen',
        'Camera',
        'Truck',
        'Folder',
        'DeviceMobile',
        'Users',
        'CreditCard',
        'Clock',
        'ShieldExclamation',
        'WrenchScrewdriver',
      ].map(icon => ({ icon, tooltip: null }))
    },
  },
})

const emit = defineEmits(['update:modelValue', 'change'])

const selected = ref(props.modelValue)

function pickIcon(icon) {
  selected.value = icon
  updateModelValue(icon)
}

function updateModelValue(value) {
  emit('update:modelValue', value)
  emit('change', value)
}

watch(() => props.modelValue, pickIcon)
</script>
